package com.kzj.mls.activity;

import android.content.Intent;
import android.os.Bundle;

import android.view.View;
import android.widget.RelativeLayout;

import com.ab.util.AbViewUtil;
import com.alibaba.fastjson.JSON;
import com.kzj.mls.R;
import com.kzj.mls.alibabaPay.SignUtils;
import com.kzj.mls.beans.AlibabaOrderInfo;
import com.kzj.mls.beans.BookDateTime;
import com.kzj.mls.beans.CloseActivityBean;
import com.kzj.mls.beans.ServiceBookBean;
import com.kzj.mls.global.App;
import com.kzj.mls.global.Constant;
import com.kzj.mls.recyclerCard.basic.MaterialListView;
import com.kzj.mls.recyclerCard.basic.OnButtonPressListener;
import com.kzj.mls.recyclerCard.card.Card;
import com.kzj.mls.recyclerCard.card.other.SelectCouponsCard;
import com.kzj.mls.recyclerCard.card.service.ServiceOrderCard;
import com.kzj.mls.recyclerCard.cardView.ServiceOrderCardView;
import com.kzj.mls.request.BaseResponse;
import com.kzj.mls.request.ICallBackForRequestServer;
import com.kzj.mls.request.RequestServerManager;
import com.kzj.mls.widget.dialog.ContainerDialog;
import com.umeng.analytics.MobclickAgent;

import de.greenrobot.event.EventBus;

/**
 * Created by xyg on 2015/11/4.
 */
public class ServiceOrderActivity extends GBaseActivity implements ContainerDialog.CardOnClick {

    MaterialListView materialListView;
    public String sid;
    public static String TagSID = "TagSID";
    RelativeLayout relativeLayoutBottom;
    private ServiceOrderCard serviceOrderCard;
    private BookDateTime bookDateTime;

    private ContainerDialog containerDialog;

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_CHECK_FLAG = 2;
    private String order_id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentViewFor720_1280(R.layout.template_materlistview);
        findViewByIds();
        initDatas();
        fillArrayInListView();
        TaskGetServiceBook(App.getInstance().getLongitude(), App.getInstance().getLatitude(), getIntent().getStringExtra(TagSID), App.getInstance().getCity());
    }

    @Override
    protected void findViewByIds() {
        materialListView = (MaterialListView) findViewById(R.id.material_listview);

    }

    @Override
    protected void initDatas() {
        sid = getIntent().getStringExtra(TagSID);
        setTopTitle("服务预约");
        setLeftImg(View.VISIBLE, R.drawable.back);
        EventBus.getDefault().register(this);
        containerDialog = ContainerDialog.createDialog(this);
        containerDialog.setCardOnClick(this);
        containerDialog.setListViewHeight(AbViewUtil.scaleValue(this, 105 * 5));

    }

    @Override
    protected void fillArrayInListView() {
        //serviceOrderCard=new ServiceOrderCard(this);
        // materialListView.add(serviceOrderCard);

    }

    /**
     * @param serviceAddrEntity
     */
    public void onEventMainThread(ServiceBookBean.ServiceAddrEntity serviceAddrEntity) {
        for (int i = 0; i < serviceOrderCard.getServiceBookBean().getService_addr().size(); i++) {
            if (serviceAddrEntity.getStore_id().equals(serviceOrderCard.getServiceBookBean().getService_addr().get(i).getStore_id())) {
                serviceOrderCard.getServiceBookBean().getService_addr().remove(i);
            }
        }
        serviceOrderCard.getServiceBookBean().getService_addr().add(0, serviceAddrEntity);
        materialListView.getAdapter().notifyDataSetChanged();
    }


    public void onEventMainThread(BookDateTime bookDateTime) {
        serviceOrderCard.setBookDateTime(bookDateTime);
        materialListView.getAdapter().notifyDataSetChanged();
    }

    public void onEventMainThread(ServiceBookBean serviceBookBean) {
        serviceOrderCard.setServiceBookBean(serviceBookBean);
        materialListView.getAdapter().notifyDataSetChanged();
    }

    private void TaskGetServiceBook(String lng, String lat, String goods_id, String city) {
        RequestServerManager.getInstance().handleMethod((GBaseActivity) getActivity(), null, null, false,
                Constant.getRootUrl() + Constant.Action.Action_booking, RequestServerManager.getInstance().
                        getRequestParams(Constant.Action.Action_booking, lng, lat, goods_id, city), BaseResponse.class, new ICallBackForRequestServer<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse result) {

                        final ServiceBookBean serviceBookBean = JSON.parseObject(JSON.toJSONString(result.getRetval()), ServiceBookBean.class);


                        serviceOrderCard = new ServiceOrderCard(ServiceOrderActivity.this);
                        String date = serviceBookBean.getBooking_date().get(0);
                        String time = "";
                        for (int i = 0; i < serviceBookBean.getBooking_time().size(); i++) {
                            if (serviceBookBean.getBooking_time().get(i).getIs_use().equals("true")) {
                                time = serviceBookBean.getBooking_time().get(i).getTime();
                                break;
                            }
                        }

                        bookDateTime = new BookDateTime();
                        bookDateTime.setBooking_date(date);
                        bookDateTime.setBooking_time(time);
                        serviceOrderCard.setSid(sid);
                        serviceOrderCard.setBookDateTime(bookDateTime);
                        serviceOrderCard.setServiceBookBean(serviceBookBean);
                        serviceOrderCard.setOnNormalButtonPressedListener(new OnButtonPressListener() {
                            @Override
                            public void onButtonPressedListener(View view, Card card) {
                                switch (view.getId()) {
                                    case R.id.textView_coupon:
                                        if (serviceBookBean.getCoupon().size() != 0)
                                            containerDialog.show();
                                        break;
                                }
                            }
                        });
                        materialListView.add(serviceOrderCard);

                        //将优惠劵加入dialog
                        for (int i = 0; i < serviceBookBean.getCoupon().size(); i++) {
                            if (i == 0) {
                                SelectCouponsCard selectCouponsCard = new SelectCouponsCard(ServiceOrderActivity.this);
                                ServiceBookBean.CouponEntity couponEntity = new ServiceBookBean.CouponEntity();
                                couponEntity.setCoupon_name("不使用优惠劵");
                                selectCouponsCard.setCouponEntity(couponEntity);
                                containerDialog.addCard(selectCouponsCard);
                            }
                            SelectCouponsCard selectCouponsCard = new SelectCouponsCard(ServiceOrderActivity.this);
                            selectCouponsCard.setCouponEntity(serviceBookBean.getCoupon().get(i));
                            containerDialog.addCard(selectCouponsCard);
                        }

                        // materialListView.getAdapter().notifyDataSetChanged();
                    }

                    @Override
                    public void onFail(int type, String errorMsg, String json) {
                        App.getInstance().showToast(errorMsg + "");
                    }
                });
    }


    //优惠劵选择的回调函数
    @Override
    public void CardOnClickListener(View view, Card card) {
        containerDialog.dismiss();
        if (((SelectCouponsCard) card).getCouponEntity().getCoupon_id() == null) {
            serviceOrderCard.setCouponIndex(-1);
        } else {
            for (int i = 0; i < serviceOrderCard.getServiceBookBean().getCoupon().size(); i++) {
                if (((SelectCouponsCard) card).getCouponEntity().getCoupon_id().equals(serviceOrderCard.getServiceBookBean().getCoupon().get(i).getCoupon_id())) {
                    serviceOrderCard.setCouponIndex(i);
                    break;
                }
            }
        }
        materialListView.getAdapter().notifyDataSetChanged();
    }





    /**
     * create the order info. 创建订单信息
     */
    public String getOrderInfo(AlibabaOrderInfo alibabaOrderInfo) {

        // 签约合作者身份ID
        String orderInfo = "partner=" + "\"" + alibabaOrderInfo.getPartner() + "\"";

        // 签约卖家支付宝账号
        orderInfo += "&seller_id=" + "\"" + alibabaOrderInfo.getSeller() + "\"";

        // 商户网站唯一订单号
        orderInfo += "&out_trade_no=" + "\"" + alibabaOrderInfo.getOrder_sn() + "\"";

        // 商品名称
        orderInfo += "&subject=" + "\"" + alibabaOrderInfo.getSubject() + "\"";

        // 商品详情
        orderInfo += "&body=" + "\"" + alibabaOrderInfo.getSubject() + "\"";

        // 商品金额
        orderInfo += "&total_fee=" + "\"" + alibabaOrderInfo.getOrder_amount() + "\"";

        // 服务器异步通知页面路径
        orderInfo += "&notify_url=" + "\"" + alibabaOrderInfo.getNotify_url()
                + "\"";

        // 服务接口名称， 固定值
        orderInfo += "&service=\"mobile.securitypay.pay\"";

        // 支付类型， 固定值
        orderInfo += "&payment_type=\"1\"";

        // 参数编码， 固定值
        orderInfo += "&_input_charset=\"utf-8\"";

        // 设置未付款交易的超时时间
        // 默认30分钟，一旦超时，该笔交易就会自动被关闭。
        // 取值范围：1m～15d。
        // m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
        // 该参数数值不接受小数点，如1.5h，可转换为90m。
        orderInfo += "&it_b_pay=\"30m\"";

        // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
        // orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

        // 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
        orderInfo += "&return_url=\"m.alipay.com\"";

        // 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
        // orderInfo += "&paymethod=\"expressGateway\"";

        return orderInfo;
    }

    /**
     * sign the order info. 对订单信息进行签名
     *
     * @param content 待签名订单信息
     */
    public String sign(String content, AlibabaOrderInfo alibabaOrderInfo) {
        return SignUtils.sign(content, alibabaOrderInfo.getPrivatekey());
    }

    /**
     * get the sign type we use. 获取签名方式
     */
    public String getSignType() {
        return "sign_type=\"RSA\"";

    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        ServiceOrderCardView.serviceSiteType = ServiceOrderCardView.serviceSiteTypeDaoDian;
        super.onDestroy();
    }

    public void onEventMainThread(CloseActivityBean closeActivityBean) {

        if (closeActivityBean.isSuccess()) {
            if (closeActivityBean.getFromActivity().equals(ServiceOrderCardView.thisFlag)) {
                Intent intent = new Intent(ServiceOrderActivity.this, PaySuccessActivity.class);
                intent.putExtra("order_bean", closeActivityBean.getOrderBean());
                startActivity(intent);
            }
        } else {
            Intent intent = new Intent(ServiceOrderActivity.this, OrderWebActivity.class);
            intent.putExtra("order_bean", closeActivityBean.getOrderBean());
            startActivity(intent);
        }
        finish();
    }
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(getClass().getSimpleName()); //统计页面(仅有Activity的应用中SDK自动调用，不需要单独写)
        MobclickAgent.onResume(this);          //统计时长
    }
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(getClass().getSimpleName()); // （仅有Activity的应用中SDK自动调用，不需要单独写）保证 onPageEnd 在onPause 之前调用,因为 onPause 中会保存信息
        MobclickAgent.onPause(this);
    }
}
